package com.huiyan.hysys.third;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;


public class JwtUtil {
    //生成
    public static String createJwt(String msg){
        //指定签名的算法
        SignatureAlgorithm algorithm=SignatureAlgorithm.HS256;
        //建造者对象
        JwtBuilder builder= Jwts.builder().
                signWith(algorithm,createKey()).//设置签名的密钥
                setId(UUID.randomUUID().toString()).//设置唯一标记，防止：重放攻击
                setIssuedAt(new Date()).//设置生成的时间
                setSubject(msg);//设置存储的内容
        //生成令牌
        return builder.compact();

    }
    //解析
    public static String parseJwt(String jwt){
        return Jwts.parser().
                setSigningKey(createKey()).
                parseClaimsJws(jwt).
                getBody().getSubject();
    }
    //生成密钥
    private static Key createKey(){
        String key="idler_lx";
        SecretKey secretKey=new SecretKeySpec(Base64.getEncoder().encode(key.getBytes()),"AES");
        return secretKey;
    }
}
